package com.xs.shop.marketing.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xs.shop.common.exceptions.BusinessException;
import com.xs.shop.common.exceptions.enums.Resp;
import com.xs.shop.marketing.model.entity.Coupon;
import com.xs.shop.marketing.model.entity.PointLog;
import com.xs.shop.marketing.model.vo.CouponInfoVO;
import com.xs.shop.marketing.model.vo.CouponPageQueryVO;
import com.xs.shop.marketing.model.vo.PointLogListVO;
import com.xs.shop.marketing.model.vo.UserCouponVO;
import com.xs.shop.marketing.service.handlers.BaseContextHandler;
import com.xs.shop.marketing.service.mapper.CouponMapper;
import com.xs.shop.marketing.service.service.CouponService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xs
 * @since 2025-07-16
 */
@Service
@Slf4j
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {

    @Resource
    private CouponMapper couponMapper;

    public Integer checkUserCouponStatus(Coupon coupon){
        //usercoupon表里为1时不修改
        UserCouponVO userCoupon = couponMapper.getUserCoupon(BaseContextHandler.get(), coupon.getId());
        if(userCoupon.getStatus() == 1){
            return 1;
        }
        Integer status;
        if(LocalDateTime.now().isAfter(coupon.getStartTime()) && LocalDateTime.now().isBefore(coupon.getEndTime())){
            status = 0;
        }else if(LocalDateTime.now().isAfter(coupon.getEndTime())){
            status = 2;
        }else{
            status = 3;
        }

        log.info("status will be updated now:{}",status);
        couponMapper.updateMemberCouponStatus(status,
                LocalDateTime.now(),
                BaseContextHandler.get(),
                coupon.getId());
        return status;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Coupon addCoupon(Coupon coupon) {
        // 设置默认值
        coupon.setCreatedAt(LocalDateTime.now());
        coupon.setUpdatedAt(LocalDateTime.now());

        Long adminId = BaseContextHandler.get();
        if (adminId != null) {
            coupon.setCreatedBy(adminId);
            coupon.setUpdatedBy(adminId);
        }
        this.save(coupon);
        return coupon;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCoupon(Long couponId) {
        if (couponId == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        return this.removeById(couponId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Coupon updateCoupon(Coupon coupon) {
        if (coupon == null || coupon.getId() == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        coupon.setUpdatedAt(LocalDateTime.now());
        coupon.setUpdatedBy(BaseContextHandler.get());
        this.updateById(coupon);
        return coupon;
    }

    @Override
    public Coupon getCouponByCouponId(Long couponId) {
        if (couponId == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        Coupon coupon = this.getById(couponId);
        return coupon;
    }

    @Override
    public IPage<CouponPageQueryVO> pageQuery(Integer current, Integer pageSize, Integer status) {
        Long memberId = BaseContextHandler.get();

        if (memberId == null) {
            throw new BusinessException(Resp.MEMBER_NOT_EXIST);
        }

        // 调用Mapper方法进行分页查询
        List<CouponPageQueryVO> couponPageQueryVOList = couponMapper.pageQueryUserCoupons(memberId, status);
        IPage<CouponPageQueryVO> pageVO = new Page<>(current, pageSize);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for(CouponPageQueryVO couponPageQueryVO : couponPageQueryVOList){
            // 进行用户所持有的优惠券的状态判断
            Integer newStatus = this.checkUserCouponStatus(this.getById(couponPageQueryVO.getId()));
            couponPageQueryVO.setStatus(newStatus);
            if (couponPageQueryVO.getStartTime() != null) {
                String dateStr = couponPageQueryVO.getStartTime().format(formatter);
                couponPageQueryVO.setStartTimeStr(dateStr); // 假设有 dateStr 字段
            }
            if (couponPageQueryVO.getEndTime() != null) {
                String dateStr = couponPageQueryVO.getEndTime().format(formatter);
                couponPageQueryVO.setEndTimeStr(dateStr); // 假设有 dateStr 字段
            }
        }
        pageVO.setRecords(couponPageQueryVOList);
        return pageVO;
    }

    @Override
    public Integer deleteMemberCoupon(Long couponId) {
        Long memberId = BaseContextHandler.get();

        if (memberId == null) {
            throw new BusinessException(Resp.MEMBER_NOT_EXIST);
        }

        Integer res = couponMapper.deleteMemberCoupon(memberId, couponId);
        if (res == 0) {
            throw new BusinessException(Resp.FAIL);
        }

        return res;
    }

    @Override
    public List<CouponInfoVO> getCouponInfoList() {
        Long memberId = BaseContextHandler.get();

        if (memberId == null) {
            throw new BusinessException(Resp.MEMBER_NOT_EXIST);
        }

        // 调用Mapper方法进行分页查询
        List<CouponInfoVO> couponInfoVOList = couponMapper.couponInfoListQuery(memberId);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for(CouponInfoVO couponInfoVO : couponInfoVOList){
            // 进行用户所持有的优惠券的状态判断
            Integer newStatus = this.checkUserCouponStatus(this.getById(couponInfoVO.getId()));
            couponInfoVO.setStatus(newStatus);
            if (couponInfoVO.getStartTime() != null) {
                String dateStr = couponInfoVO.getStartTime().format(formatter);
                couponInfoVO.setStartTimeStr(dateStr); // 假设有 dateStr 字段
            }
            if (couponInfoVO.getEndTime() != null) {
                String dateStr = couponInfoVO.getEndTime().format(formatter);
                couponInfoVO.setEndTimeStr(dateStr); // 假设有 dateStr 字段
            }
        }
        return couponInfoVOList;
    }

    @Override
    public Boolean checkUserHaveCoupon(Long couponId) {
        UserCouponVO userCouponVO = couponMapper.getUserCoupon(BaseContextHandler.get(),couponId);
        log.info("do u already have that coupon?:{}",userCouponVO!=null);
        return userCouponVO != null ? true : false;
    }
}
